package com.appkubes.portal.admin.application.app.menu.controller;

import com.appkubes.base.core.entity.vo.AppKeyVO;
import com.appkubes.common.Response;
import com.appkubes.common.exception.BusinessException;
import com.appkubes.portal.admin.application.app.menu.entity.dto.PortalAppMenuDTO;
import com.appkubes.portal.admin.application.app.menu.entity.vo.MenuAddVO;
import com.appkubes.portal.admin.application.app.menu.entity.vo.MenuAdminGetVO;
import com.appkubes.portal.admin.application.app.menu.entity.vo.MenuDelVO;
import com.appkubes.portal.admin.application.app.menu.entity.vo.MenuGetVO;
import com.appkubes.portal.admin.application.auth.service.KeyCloakRoleService;
import com.appkubes.portal.admin.application.auth.service.KeyCloakUserService;
import com.appkubes.cloud.config.params.paramValid.ParamValid;
import com.appkubes.portal.admin.facility.util.MenuTree;
import com.appkubes.portal.core.controller.BasePortalAppMenuController;
import com.appkubes.portal.core.entity.PortalAppMenu;
import com.appkubes.portal.core.entity.PortalAppMenuRole;
import com.appkubes.portal.core.service.BasePortalAppMenuRoleService;
import com.appkubes.portal.core.service.BasePortalAppMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "菜单模块")
@RestController
@RequestMapping("/app/menu")
public class AppMenuController extends BasePortalAppMenuController {

    @Resource
    KeyCloakRoleService roleService;

    @Resource
    BasePortalAppMenuRoleService menuRoleService;

    @Resource
    BasePortalAppMenuService menuService;

    @Resource
    KeyCloakUserService keyCloakUserService;

    @Resource
    KeyCloakRoleService keyCloakRoleService;

    @ApiOperation("获取根菜单")
    @GetMapping("/root")
    public Response root(@ParamValid AppKeyVO appKeyVO) {
        PortalAppMenu portalAppMenu = new PortalAppMenu();
        BeanUtils.copyProperties(appKeyVO, portalAppMenu);
        portalAppMenu.setMenuLevel(0);

        List<PortalAppMenu> appMenuList = this.selectListByEntity(portalAppMenu);

        return Response.success(appMenuList);
    }

    @ApiOperation("获取菜单列表")
    @GetMapping("/get")
    public Response get(@ParamValid MenuGetVO menuGetVO) {
        PortalAppMenu portalAppMenu = new PortalAppMenu();
        BeanUtils.copyProperties(menuGetVO, portalAppMenu);

        IPage<?> pageResult = this.selectPageByEntity(portalAppMenu, menuGetVO);
        return Response.success(pageResult);
    }

    @ApiOperation("获取全部菜单")
    @GetMapping("/getAll")
    public Response getAll() {
        QueryWrapper<PortalAppMenu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.orderByAsc("sort");
        List<PortalAppMenu> pageResult = menuService.list(menuQueryWrapper);
        List<PortalAppMenuDTO> appMenuList = new ArrayList<>();
        for (PortalAppMenu menuNode : pageResult) {
            PortalAppMenuDTO appMenu = new PortalAppMenuDTO();
            appMenu.setAppKey(menuNode.getAppKey());
            appMenu.setMenuKey(menuNode.getMenuKey());
            appMenu.setAction(menuNode.getAction());
            appMenu.setRedirectUrl(menuNode.getRedirectUrl());
            appMenu.setComponent(menuNode.getComponent());
            appMenu.setHidden(menuNode.getHidden());
            appMenu.setMenuName(menuNode.getMenuName());
            appMenu.setMenuLevel(menuNode.getMenuLevel());
            appMenu.setMenuType(menuNode.getMenuType());
            appMenu.setParentMenuKey(menuNode.getParentMenuKey());
            appMenu.setIcon(menuNode.getIcon());
            appMenu.setSort(menuNode.getSort());
            appMenuList.add(appMenu);
        }
        MenuTree menuTree = new MenuTree(appMenuList);
        appMenuList = menuTree.builTree();
        return Response.success(appMenuList);
    }

    @ApiOperation("编辑菜单")
    @PostMapping("/save")
    public Response save(@ParamValid MenuAddVO menuAddVO) {
        PortalAppMenu appMenu = new PortalAppMenu();
        BeanUtils.copyProperties(menuAddVO, appMenu);

        String parentMenuKey = menuAddVO.getParentMenuKey();
        if (parentMenuKey != null && !parentMenuKey.equals("")) {
            PortalAppMenu parentMenu = (PortalAppMenu) this.getById(parentMenuKey);
            if (parentMenu == null) {
                return Response.error("没有该父菜单");
            }
            appMenu.setMenuLevel(parentMenu.getMenuLevel() + 1);
        }
        Boolean flag = this.saveOrUpdate(appMenu);
        return Response.success(flag);
    }

    @Override
    public Boolean checkDelByIdCondition(Serializable id) {
        //删除菜单, 检查有没有子菜单
        PortalAppMenu portalAppMenu = new PortalAppMenu();
        portalAppMenu.setParentMenuKey(id.toString());

        Integer count = this.selectCount(portalAppMenu);
        if (count > 0) {
            throw new BusinessException("存在子菜单，不允许删除");
        }
        return true;
    }

    @ApiOperation("菜单信息")
    @PostMapping("/info")
    public Response info(@ParamValid MenuDelVO menuDelVO) {
        PortalAppMenu portalAppMenu = new PortalAppMenu();
        QueryWrapper<PortalAppMenu> queryWrapper = new QueryWrapper<>();
        portalAppMenu.setMenuKey(menuDelVO.getMenuKey());
        queryWrapper.setEntity(portalAppMenu);
        portalAppMenu = (PortalAppMenu) this.getOne(queryWrapper);
        if (portalAppMenu == null) {
            return Response.error("查询不到信息");
        }
        return Response.success(portalAppMenu);
    }

//    @ApiOperation("获取用户有权限的菜单")
//    @GetMapping("/getByUser")
//    public Response getMenuByUser(@ParamValid MenuAdminGetVO menuAdminGetVO) {
//        Map<?, ?> menuMap = appMenuService.getAdminMenu(menuAdminGetVO);
//        return Response.success(menuMap);
//    }

    @ApiOperation("获取用户有权限的菜单")
    @GetMapping("/getMenuByUser")
    public Response getMenuByUser(@ParamValid MenuAdminGetVO menuAdminGetVO) {
        List<RoleRepresentation> roleList = keyCloakRoleService.getUserClientRoleList(menuAdminGetVO.getAdminKey());

        if (roleList.size() == 0) {
            return Response.error("用户未设置角色");
        }
        List<String> roleArr = new ArrayList<>();

        for (RoleRepresentation role : roleList) {
            roleArr.add(role.getName());
        }
        String[] roles = new String[roleArr.size()];
        roleArr.toArray(roles);
        QueryWrapper<PortalAppMenuRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_code", roles);
        queryWrapper.eq("status", "ACTIVE");
        List<PortalAppMenuRole> roleMenus = menuRoleService.list(queryWrapper);

        List<String> menusArr = new ArrayList<>();
        for (PortalAppMenuRole menuRole : roleMenus) {
            menusArr.add(menuRole.getMenuKey());
        }
        String[] menuKeys = new String[menusArr.size()];
        menusArr.toArray(menuKeys);
        QueryWrapper<PortalAppMenu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.in("menu_key", menuKeys);
        menuQueryWrapper.orderByAsc("sort");
        List<PortalAppMenu> menuList = menuService.list(menuQueryWrapper);
        List<PortalAppMenuDTO> appMenuList = new ArrayList<>();
        for (PortalAppMenu menuNode : menuList) {
            PortalAppMenuDTO appMenu = new PortalAppMenuDTO();
            appMenu.setAppKey(menuNode.getAppKey());
            appMenu.setMenuKey(menuNode.getMenuKey());
            appMenu.setAction(menuNode.getAction());
            appMenu.setRedirectUrl(menuNode.getRedirectUrl());
            appMenu.setComponent(menuNode.getComponent());
            appMenu.setHidden(menuNode.getHidden());
            appMenu.setMenuName(menuNode.getMenuName());
            appMenu.setMenuLevel(menuNode.getMenuLevel());
            appMenu.setMenuType(menuNode.getMenuType());
            appMenu.setParentMenuKey(menuNode.getParentMenuKey());
            appMenu.setIcon(menuNode.getIcon());
            appMenu.setSort(menuNode.getSort());
            appMenuList.add(appMenu);
        }
        MenuTree menuTree = new MenuTree(appMenuList);
        appMenuList = menuTree.builTree();
        return Response.success(appMenuList);
    }
}
